package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.CustomException;
import com.example.common.Result;
import com.example.dto.UserDto;
import com.example.entity.*;
import com.example.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hotta
 * @since 2023-05-31
 */
@Api(tags = {"用户接口列表"})
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserAService userAService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private UserWagesService userWagesService;

    @Autowired
    private ExpensesUserService expensesUserService;


    /**
     * 登录
     *
     * @param user
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,user.getUsername());
        User one = userService.getOne(userLambdaQueryWrapper);
        if(one.getStatus()!=1){
            return Result.fail(20002, "用户已被禁用，无法登录");
        }

        log.info("user = " + user);
        Map<String, Object> data = userService.login(user);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(20002, "用户名或密码错误");
    }

    /**
     * 根据token 从redis中获取用户信息
     *
     * @param token
     * @return
     */
    @ApiOperation("用户登录验证")
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestParam String token) {
        log.info(token);
        Map<String, Object> data = userService.getUserInfo(token);

        log.info("------------------------------{}", data);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(20003, "登录信息无效，请重新登录");
    }

    /**
     * 登出
     *
     * @param token
     * @return
     */
    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token) {
        userService.logout(token);
        return Result.success();
    }

    /**
     * user页面的分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @param phone
     * @return
     */
    @ApiOperation("用户分页查询")
    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(int page, int pageSize, String name, String phone) {
        log.info("page = {},pageSize = {},name = {},phone={}", page, pageSize, name, phone);

        Page<User> userPage = new Page<>(page, pageSize);
        Page<UserDto> userDtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), User::getUsername, name);
        userService.page(userPage, userLambdaQueryWrapper);

        List<User> userPageRecords = userPage.getRecords();

        List<UserDto> collect = userPageRecords.stream().map(item -> {

            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(item, userDto);

            LambdaQueryWrapper<UserA> userALambdaQueryWrapper = new LambdaQueryWrapper<>();
            userALambdaQueryWrapper.eq(UserA::getUserId, item.getId());
            UserA one = userAService.getOne(userALambdaQueryWrapper);

            userDto.setDepartmentId(one.getDepartmentId());
            userDto.setPositionId(one.getPositionId());

            log.info("{}", userDto);

            LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            departmentLambdaQueryWrapper.eq(Department::getId, one.getDepartmentId());
            LambdaQueryWrapper<Position> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            positionLambdaQueryWrapper.eq(Position::getId, one.getPositionId());

            userDto.setDepartmentName(departmentService.getOne(departmentLambdaQueryWrapper).getName());
            userDto.setPositionName(positionService.getOne(positionLambdaQueryWrapper).getName());

            log.info("{}", userDto);

            return userDto;

        }).collect(Collectors.toList());

        userDtoPage.setRecords(collect);

        Map<String, Object> map = new HashMap<>();
        map.put("total", userPage.getTotal());
        map.put("rows", userDtoPage.getRecords());
        return Result.success(map);
    }

    @ApiOperation("新增用户")
    @PostMapping
    public Result<?> addUser(@RequestBody UserDto userDto) {
        log.info(userDto.toString());
        userDto.setPassword(passwordEncoder.encode("123456"));
        userService.addUser(userDto);
        return Result.success("新增用户成功");
    }

    @ApiOperation("修改用户")
    @PutMapping
    public Result<?> updateUser(HttpServletRequest request,@RequestBody UserDto userDto) {
        log.info(userDto.toString());

        String header = request.getHeader("X-Token");
        Object o = redisTemplate.opsForValue().get(header);
        User user = (User) o;

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId,userDto.getId());
        User one = userService.getOne(userLambdaQueryWrapper);
        if (user.getId() == one.getId() && user.getStatus()!=userDto.getStatus() ){
            log.info("------------------------------");
            return Result.fail("该用户已登录，不能修改其状态");
        }

        if(one.getStatus() != userDto.getStatus() && one.getStatus()==1){
            LambdaQueryWrapper<UserWages> userWagesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userWagesLambdaQueryWrapper.eq(UserWages::getUserId, userDto.getId());
            long count = userWagesService.count(userWagesLambdaQueryWrapper);

            LambdaQueryWrapper<ExpensesUser> expensesUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            expensesUserLambdaQueryWrapper.eq(ExpensesUser::getUserId, userDto.getId());
            long count1 = expensesUserService.count(expensesUserLambdaQueryWrapper);

            if (count > 0 || count1 > 0) {
                return Result.fail("该用户正在使用，不能修改其状态");
                    }
        }


        userService.updateUser(userDto);
        return Result.success("修改用户成功");
    }

    @ApiOperation("返回到修改界面的查询用户")
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public Result<?> deleteUserById(HttpServletRequest request,@PathVariable Long id) {

        String header = request.getHeader("X-Token");
        Object o = redisTemplate.opsForValue().get(header);
        User user = (User) o;


        LambdaQueryWrapper<UserWages> userWagesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userWagesLambdaQueryWrapper.eq(UserWages::getUserId, id);
        long count = userWagesService.count(userWagesLambdaQueryWrapper);

        LambdaQueryWrapper<ExpensesUser> expensesUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        expensesUserLambdaQueryWrapper.eq(ExpensesUser::getUserId, id);
        long count1 = expensesUserService.count(expensesUserLambdaQueryWrapper);


        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId,id);
        User one = userService.getOne(userLambdaQueryWrapper);
        if(user.getUsername().equals(one.getUsername())){
            throw new CustomException("用户已经登录，不能删除");

        }
        if (count > 0 || count1 > 0) {
            throw new CustomException("该员工已关联其他数据，不能删除");
        } else {
            userService.deleteUserById(id);
            return Result.success("删除用户成功");
        }
    }

    @ApiOperation("修改界面的用户数据")
    @GetMapping("/name")
    public Result<?> getUserName(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(user.getStatus() != null, User::getStatus, user.getStatus());

        List<User> list = userService.list(wrapper);

        log.info("{}", list);
        return Result.success(list);
    }

    @ApiOperation("首页查询用户数据")
    @GetMapping("/listOne")
    public Result<?> getUserName(HttpServletRequest request) {

        String header = request.getHeader("X-Token");
        Object o = redisTemplate.opsForValue().get(header);
        User user = (User) o;

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, user.getId());
        User one3 = userService.getOne(userLambdaQueryWrapper);

        LambdaQueryWrapper<UserA> userALambdaQueryWrapper = new LambdaQueryWrapper<>();
        userALambdaQueryWrapper.eq(UserA::getUserId, user.getId());
        UserA one = userAService.getOne(userALambdaQueryWrapper);

        LambdaQueryWrapper<Position> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        positionLambdaQueryWrapper.eq(Position::getId, one.getPositionId());
        Position one1 = positionService.getOne(positionLambdaQueryWrapper);

        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(Department::getId, one.getDepartmentId());
        Department one2 = departmentService.getOne(departmentLambdaQueryWrapper);

        user.setDepartmentName(one2.getName());
        user.setPositionName(one1.getName());
        user.setUsername(one3.getUsername());
        user.setPhone(one3.getPhone());
        user.setEmail(one3.getEmail());


        log.info("{}", user);

        return Result.success(user);
    }


}